// 获取uuid
function build_uuid() {
    function simple() {
        return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
    }
    return (simple() + simple() + "-" + simple() + "-" + simple() + "-" + simple() + "-" + simple() + simple() + simple());
}

// 寻找文章的 title  也就是h标签
function findTitle(node_path) {
    let flatArr = [];
    // console.log(node_path)
    // console.log(node_path, $(node_path), $(node_path).children("h1,h2,h3,h4"));
    $(node_path).find("h1,h2,h3,h4").each(function(index, value, arr){
        let tag_name = value.tagName;
        let uuid = build_uuid();
        let node_level = 0;
        let node_size = 0;
        // 为h标签加上id
        $(this).attr("id",uuid);
        // console.log(value.className);
        switch(tag_name) {
            case "H1":
                node_level = 1;
                node_size = 16;
                break
            case "H2":
                node_level = 2;
                node_size = 14;
                break
            case "H3":
                node_level = 3;
                node_size = 12;
                break
            case "H4":
                node_level = 4;
                node_size = 10;
                break
            default:
                
        }
        flatArr.push({
            level: node_level,
            tag_value: value.innerText,
            l_id: uuid,
            font_size: node_size
        })
        // 组建字典 分配等级
    })
    // console.log(flatArr);
    return flatArr;
}



// 构建父级关系函数
function toTree2(flatArr) {
    var resultArr = []; // 结果集数组
    var stack = []; // 栈数组
    var collector = resultArr; // 收集器
    flatArr.forEach((levelItem, index) => {
        if (stack.length == 0) { // 第一次循环时没有任何内容，则默认将第一个元素入栈
            stack.push(levelItem);
            collector.push(levelItem);
            levelItem.children = [];
            levelItem.parentCollector = resultArr; // 存储父级
            // 改变收集器为当前级别的子集
            collector = levelItem.children;
        } else {
            let lastestLeveInStack = stack[stack.length - 1]; // 获取栈顶的元素，即最近如入栈的元素

            if (lastestLeveInStack.level >= levelItem.level) { // 说明遇到同级节点了
                let kickOutLevel = stack.pop(); // 移除栈顶的元素
                stack.push(levelItem); // 将当前元素入栈


                // 当前级别与被移除栈顶的级别属于同一级别，因此当前级别需要添加进相同的父级中
                kickOutLevel.parentCollector.push(levelItem);
                levelItem.parentCollector = kickOutLevel.parentCollector; // 存储父级
                delete kickOutLevel.parentCollector;
                if (kickOutLevel.children.length == 0) {
                    delete kickOutLevel.children;
                }

                levelItem.children = [];
                collector = levelItem.children;
            } else {
                let prevLevelItem = collector[collector.length - 1];
                // 如果上一个元素的级别比当前这个元素小，则说明当前元素应为上一个元素的子集
                if (prevLevelItem && (prevLevelItem.level < levelItem.level)) {
                    let parentCollector = stack[stack.length - 1];
                    stack.push(prevLevelItem);
                    prevLevelItem.children = [];
                    prevLevelItem.parentCollector = parentCollector.children;
                    collector = prevLevelItem.children;
                }
                collector.push(levelItem);
            }
        }
    });
    // 移除元素的parentCollector属性
    flatArr.forEach(levelItem => {
        if (levelItem.parentCollector) {
            delete levelItem.parentCollector;
        }
    });
    return resultArr;
}

function createNodeByHtmlStr(htmlStr){
    var div = document.createElement('div');
    div.innerHTML = htmlStr;
    var children = div.children;
    div = null;
    return children;
  }
  

// 根据树状结构数据生成章节目录dom树
function getChapterDomTree(chapterTreeData, parentNode) {
    // 如果没有父级单位 则创建一个父级单位 也就是第一次递归的时候 需要初始化一下
    if (!parentNode) {
        parentNode = document.createElement('nav');
        parentNode.className = "nav nav-pills flex-column";
    }
    chapterTreeData.forEach(chapterItem => {
        // var itemDom = createNodeByHtmlStr('<li><a class="toc-level-' + chapterItem.level + '" href="#' + chapterItem.l_id + '">' + chapterItem.tag_value + '</a></li>')[0];
        // var itemDom = createNodeByHtmlStr('<a class="nav-link moving-tab" href="#' + chapterItem.l_id + '">' + chapterItem.tag_value +' </a>')
        var itemDom = document.createElement('a');
        itemDom.className = "nav-link moving-tab";
        // console.log(chapterItem.node_size);
        itemDom.style.cssText = `color: rgb(245 245 245);; font-weight: 600; font-size: ${chapterItem.font_size}px;`
        itemDom.href = `#${chapterItem.l_id}`;
        itemDom.innerText = chapterItem.tag_value;
        parentNode.appendChild(itemDom);
        if (chapterItem.children) {
            // var catalogList = createNodeByHtmlStr('<nav class="nav nav-pills flex-column"></nav>')[0];
            var catalogList = document.createElement('nav');
            catalogList.className = "nav nav-pills1 flex-column";
            itemDom.appendChild(catalogList);
            getChapterDomTree(chapterItem.children, catalogList);
        }
    });
    return parentNode;
}



function showArticleIndexTree(node_path, node_p, idx=0) {
    // step1 寻找h标签
    var listArr = findTitle(node_path);
    var tree = toTree2(listArr);
    var new_node;
    var node;
    if (idx ===0 ){
        node = $(node_p);
    }else{
        node = $(node_p)[idx];
    }
    if (tree.length === 0) {
        // 移除侧边栏
        new_node = document.createElement('nav');
        new_node.className = "nav nav-pills flex-column";
        new_node.style.cssText = "margin-top: 10px; margin-bottom: 10px;"
        var itemDom = document.createElement('a');
        itemDom.innerHTML = "&nbsp;&nbsp;暂无索引";
        new_node.appendChild(itemDom);
    }else{
        // 外层滑动 <el-scrollbar>
        new_node = getChapterDomTree(tree);
    }
    // 添加样式
    new_node.style.cssText = "box-shadow: 10px 10px 5px rosybrown;margin-right: 20px;background-color: rgb(46 46 51);;";
    // style="box-shadow: 10px 10px 5px rosybrown;margin-right: 20px;background-color: antiquewhite;"
    // console.log(new_node);
    // console.log(node)
    node.append(new_node)
}

//关键
window.showArticleIndexTree = showArticleIndexTree


// export default {
//     showArticleIndexTree
// };